﻿/*
	Copyright (c) 2013 Andrew Meyer

	Permission is hereby granted, free of charge, to any person obtaining a copy of this software
	and associated documentation files (the "Software"), to deal in the Software without
	restriction, including without limitation the right to use, copy, modify, merge, publish,
	distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
	Software is furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in all copies or
	substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
	BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
	NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
	DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using Ascend;

namespace AscendViewer
{
	public enum OverlayState
	{
		Hidden,
		Normal,
		Selected
	}

	public abstract class ContentNodeViewModel : ObservableObject
	{
		#region Lifecycle
		public ContentNodeViewModel(TransformableObject data,
			Queue<TransformableObject> axisSceneAliases,
			Queue<TransformableObject> boneSceneAliases, ContentExplorerViewModel container,
			ContentNodeViewModel parent)
		{
			_container = container;

			Parent = parent;
			Data = data;
			Children = new List<ContentNodeViewModel>();

			SetupSceneAliases(axisSceneAliases, boneSceneAliases);

			SelectCommand = new InterfaceCommand(() => container.SelectedContentNode = this);
			LookAtCommand = new InterfaceCommand(() =>
				{
					container.MainWindow.MainScene.LookAt(Data);
				});
		}
		#endregion

		#region Protected Members
		protected ContentExplorerViewModel _container;
		protected TransformableObject _axisSceneAlias;
		protected TransformableObject _boneSceneAlias;
		#endregion

		#region Public Properties
		public ContentNodeViewModel Parent
		{
			get;
			private set;
		}

		public ICommand SelectCommand
		{
			get;
			private set;
		}

		public ICommand LookAtCommand
		{
			get;
			protected set;
		}

		public TransformableObject Data
		{
			get;
			private set;
		}

		public string Name
		{
			get;
			protected set;
		}

		public List<ContentNodeViewModel> Children
		{
			get;
			protected set;
		}

		public virtual string SelfAsString
		{
			get
			{
				return Data.ToString();
			}
		}

		public Type Type
		{
			get
			{
				return GetType();
			}
		}

		private bool _isSelected = false;
		public bool IsSelected
		{
			get
			{
				return _isSelected;
			}

			set
			{
				if (_isSelected == value)
				{
					return;
				}

				_isSelected = value;

				HandleSelectionChange();

				NotifyPropertyChanged("IsSelected");
			}
		}

		private bool _isExpanded = true;
		public bool IsExpanded
		{
			get
			{
				return _isExpanded;
			}

			set
			{
				if (_isExpanded == value)
				{
					return;
				}

				_isExpanded = value;
				NotifyPropertyChanged("IsExpanded");
			}
		}

		public bool CanExpand
		{
			get
			{
				return Children.Any();
			}
		}
		#endregion

		#region Public Methods
		public List<ContentNodeViewModel> SelfAndDescendants()
		{
			List<ContentNodeViewModel> list = new List<ContentNodeViewModel>();

			list.Add(this);

			foreach (ContentNodeViewModel child in Children)
			{
				list.AddRange(child.SelfAndDescendants());
			}

			return list;
		}

		public List<ContentNodeViewModel> SelfAndAncestors()
		{
			List<ContentNodeViewModel> list = new List<ContentNodeViewModel>();

			list.Add(this);

			if (Parent != null)
			{
				list.AddRange(Parent.SelfAndAncestors());
			}

			return list;
		}
		#endregion

		#region Protected Methods
		protected virtual void SetupSceneAliases(Queue<TransformableObject> axisSceneAliases,
			Queue<TransformableObject> boneSceneAliases)
		{
			_axisSceneAlias = axisSceneAliases.Dequeue();
			_boneSceneAlias = boneSceneAliases.Dequeue();
		}

		protected virtual void HandleSelectionChange()
		{
			if (IsSelected)
			{
				// Expand to this content node
				foreach (ContentNodeViewModel node in SelfAndAncestors().Skip(1))
				{
					node.IsExpanded = true;
				}
			}
		}

		protected void InitializeChildren(IEnumerable<TransformableObject> children,
			Queue<TransformableObject> axisSceneAliases,
			Queue<TransformableObject> boneSceneAliases, ContentExplorerViewModel container)
		{
			foreach (TransformableObject child in children)
			{
				Children.Add(Create(child, axisSceneAliases, boneSceneAliases, container, this));
			}
		}
		#endregion

		#region Static Methods
		public static ContentNodeViewModel Create(object obj,
			Queue<TransformableObject> axisSceneAliases,
			Queue<TransformableObject> boneSceneAliases, ContentExplorerViewModel container,
			ContentNodeViewModel parent)
		{
			if (obj is AnimatedSceneNode)
			{
				return new AnimatedContentNodeViewModel((AnimatedSceneNode)obj, axisSceneAliases,
					boneSceneAliases, container, parent);
			}
			else if (obj is ModelSceneNode)
			{
				return new ModelContentNodeViewModel((ModelSceneNode)obj, axisSceneAliases,
					boneSceneAliases, container, parent);
			}
			else if (obj is Bone)
			{
				return new BoneContentNodeViewModel((Bone)obj, axisSceneAliases, boneSceneAliases,
					container, parent);
			}
			else if (obj is Armature)
			{
				return new ArmatureContentNodeViewModel((Armature)obj, axisSceneAliases,
					boneSceneAliases, container, parent);
			}
			else
			{
				throw new NotSupportedException("Unknown content node encountered.");
			}
		}

		protected static ModelSceneNode CreateAxes(double width = 0.015, double scale = 1.0)
		{
			double length = 0.5;

			ModelSceneNode xAxis = ModelSceneNode.Create(ModelMaker.MakeCube(length, width, width,
				Colors.Red));
			ModelSceneNode yAxis = ModelSceneNode.Create(ModelMaker.MakeCube(width, length, width,
				Colors.Blue));
			ModelSceneNode zAxis = ModelSceneNode.Create(ModelMaker.MakeCube(width, width, length,
				Colors.Green));

			ModelSceneNode axes = ModelSceneNode.Create();

			xAxis.X = length / 2 + width / 2;
			axes.Children.Add(xAxis);

			yAxis.Y = length / 2 + width / 2;
			axes.Children.Add(yAxis);

			zAxis.Z = length / 2 + width / 2;
			axes.Children.Add(zAxis);

			axes.Scale = new Scale3D(scale);

			return axes;
		}

		protected static ModelSceneNode CreateBoneVisual(double length, Color color)
		{
			double halfWidth = 0.1;
			double middleLoc = -0.25;

			MeshGeometry3D mesh = new MeshGeometry3D();

			List<Point3D> vertices = new List<Point3D>
			{
				new Point3D(0, 0, 0),
				new Point3D(halfWidth, halfWidth, middleLoc),
				new Point3D(halfWidth, -halfWidth, middleLoc),
				new Point3D(-halfWidth, -halfWidth, middleLoc),
				new Point3D(-halfWidth, halfWidth, middleLoc),
				new Point3D(0, 0, -1)
			};

			mesh.Positions = new Point3DCollection
			{
				vertices[0], vertices[2], vertices[1],
				vertices[0], vertices[3], vertices[2],
				vertices[0], vertices[4], vertices[3],
				vertices[0], vertices[1], vertices[4],
				vertices[5], vertices[1], vertices[2],
				vertices[5], vertices[2], vertices[3],
				vertices[5], vertices[3], vertices[4],
				vertices[5], vertices[4], vertices[1]
			};

			ModelSceneNode bone = ModelSceneNode.Create(new GeometryModel3D
			{
				Geometry = mesh,
				Material = new DiffuseMaterial(new SolidColorBrush(color))
			});

			bone.Scale = new Scale3D(Math.Abs(length));

			return bone;
		}
		#endregion
	}
}
